##########################################################################################

library(dplyr)
library(ggplot2)
library(data.table)
library(RColorBrewer)
library(optparse)
library(ggpubr)

##########################################################################################

option_list <- list(
    make_option(c("--gene_list_file"), type = "character") ,
    make_option(c("--info_file"), type = "character") ,
    make_option(c("--type"), type = "character") ,
    make_option(c("--class_sub_file"), type = "character") ,
    make_option(c("--lollipop_file"), type = "character") ,
    make_option(c("--ccf_file"), type = "character") ,
    make_option(c("--images_path"), type = "character")
)

if(1!=1){
    
    gene_list_file <- "~/20220915_gastric_multiple/dna_combinePublic/Pyclone/selectGCClone/GCCloneGene.use.list"
    type <- "IGC"
    work_dir <- "~/20220915_gastric_multiple/dna_combinePublic"
    info_file <- paste(work_dir,"/config/STAD-useCombine.Sample.tsv",sep="")
    class_sub_file <- paste(work_dir,"/config/Class_order_sub.list",sep="")
    ccf_file <- paste(work_dir,"/mutationTime/result/All_CCF_mutTime.tsv",sep="")
	images_path <- paste(work_dir,"/images/ChooseClone",sep="")

}

###########################################################################################

parseobj <- OptionParser(option_list=option_list, usage = "usage: Rscript %prog [options]")
opt <- parse_args(parseobj)
print(opt)

gene_list_file <- opt$gene_list_file
ccf_file <- opt$ccf_file
info_file <- opt$info_file
class_sub_file <- opt$class_sub_file
images_path <- opt$images_path
lollipop_file <- opt$lollipop_file
type <- opt$type

dir.create(images_path , recursive = T)

###########################################################################################

col <- c(
  brewer.pal(9,"YlGnBu")[6],
  rgb(234,106,79,alpha=255,maxColorValue=255),
  rgb(203,24,30,alpha=255,maxColorValue=255),
  rgb(255,0,0,alpha=255,maxColorValue=255)
  )

names(col) <- c("IM" , "IGC" , "DGC" , "GC")

Variant_Types <- c("Missense_Mutation","Nonsense_Mutation","Frame_Shift_Ins","Frame_Shift_Del","In_Frame_Ins","In_Frame_Del","Splice_Site","Nonstop_Mutation")

###########################################################################################

dat_sample <- data.frame(fread( info_file ))
dat_ccf <- data.frame(fread( ccf_file ))
class_sub <- data.frame(fread(class_sub_file))
gene_list <- fread(gene_list_file , header = F)$V1

###########################################################################################

dat_ccf <- subset( dat_ccf , Variant_Classification %in% Variant_Types & Hugo_Symbol %in% gene_list )
dat_sample_use <- dat_sample[,c("Patient" , "Tumor" , "Class" , "Class_sub" , "Type" )]
dat_ccf_use <- merge( dat_sample_use , dat_ccf , by.x = "Tumor" , by.y = "Sample" )
dat_ccf_use$Class_sub <- factor( dat_ccf_use$Class_sub , levels = class_sub$Class , order = T )

dat_ccf_use[dat_ccf_use$CLS=="clonal [early]","CLS"] <- "Early"
dat_ccf_use[dat_ccf_use$CLS=="clonal [NA]","CLS"] <- "Constant"
dat_ccf_use[dat_ccf_use$CLS=="clonal [late]","CLS"] <- "Late"
dat_ccf_use[dat_ccf_use$CLS=="subclonal","CLS"] <- "Subclonal"

dat_ccf_use$vid <- paste(paste0("chr",dat_ccf_use$Chr) , dat_ccf_use$Start_Position , dat_ccf_use$REF , dat_ccf_use$ALT , sep = ":")
dat_ccf_use$strip_use <- paste0( dat_ccf_use$Patient , "\n" , dat_ccf_use$vid )
dat_ccf_use <- unique(dat_ccf_use)
dat_ccf_use$Type <- factor( dat_ccf_use$Type , levels = c("IM + IGC" , "IM + DGC" , "IM + IGC + DGC") , order = T)
dat_ccf_use <- dat_ccf_use[order(dat_ccf_use$Type),]

###############################################
plotCCF <- function(dat_ccf_use = dat_ccf_use , sample_num = sample_num , out_name = out_name , type = type){

    plot <- ggplot(dat_ccf_use , mapping = aes(Class_sub , CCF_adj , fill = Class))+
        geom_bar(position = "stack", stat = "identity") + 
        facet_grid(vars(Hugo_Symbol) , vars(Patient) , scales = "free", space = "free") +
        scale_fill_manual(values=col) +
        xlab(NULL) +
        ylim(0,1) +
        ylab("Cell Fraction")+
        #geom_text(mapping = aes(x = Class_sub , y = 1.2 , label = CLS) , size=3 , face='bold' , color="black") +
        theme_bw() +
        theme(panel.background = element_blank(),#设置背影为白色#清除网格线
            legend.position ='none',
            legend.title = element_blank() ,
            panel.grid.major=element_line(colour=NA),
            plot.title = element_text(size = 8,color="black",face='bold'),
            legend.text = element_text(size = 10,color="black",face='bold'),
            axis.text.y = element_text(size = 8,color="black",face='bold'),
            axis.title.x = element_text(size = 10,color="black",face='bold'),
            axis.title.y = element_text(size = 10,color="black",face='bold'),
            axis.ticks.x = element_blank(),
            axis.text.x = element_text(size = 8,color="black",face='bold') ,
            strip.text.x = element_text(size = 10,color="black",face='bold') ,
            strip.text.y = element_text(size = 12,color="black",face='bold')
        ) 

    ## x轴每个柱子一样宽
    p <- plot
    gp <- ggplotGrob(p)
    facet.columns <- gp$layout$l[grepl("panel", gp$layout$name)]
    x.var <- sapply(ggplot_build(p)$layout$panel_scales_x,
                    function(l) length(l$range$range))
    gp$widths[facet.columns] <- gp$widths[facet.columns] * x.var

    if(type=="DGC"){
        width=12
        height=10
    }else if(type=="IGC"){
        width=13
        height=8
    }else if(type=="All"){
        width=13
        height=8
    }
    
    pdf(out_name , width=width ,height=height)
    grid::grid.draw(gp)
    dev.off()
}

###############################################
## IM和GC共享的位点
im_sample <- unique(dat_ccf_use[dat_ccf_use$Class == "IM","strip_use"])
gc_sample <- unique(dat_ccf_use[dat_ccf_use$Class != "IM","strip_use"])
share_sample <- im_sample[im_sample %in% gc_sample]

if(length(share_sample)!=0){
    dat_plot <- dat_ccf_use[dat_ccf_use$strip_use %in% share_sample , ]

    ## 计算突变数量给基因排序
    dat_sampleNum <- dat_plot %>%
    group_by( Hugo_Symbol ) %>%
    summarize( MutNum = length(unique(Patient)) )
    dat_sampleNum <- data.frame(dat_sampleNum)
    gene_order <- dat_sampleNum[order(dat_sampleNum$MutNum , decreasing=T),"Hugo_Symbol"]
    dat_plot$Hugo_Symbol <- factor( dat_plot$Hugo_Symbol , levels = gene_order , order = T )

    out_name <- paste0( images_path , "/mutCCF.chooseGene.bar.share.",type,".pdf" ) 
    plotCCF(dat_ccf_use = dat_plot , sample_num = unique(dat_plot$strip_use) , out_name = out_name , type = type)
    
}
